#pragma once

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <stdint.h>
#include <pthread.h>
#include <iostream>

using namespace std;

class Serial
{
public:
    Serial(int nSpeed = 115200, int nBits = 8, char nEvent = 'N', int nStop = 1);
    ~Serial();  //析构
    pthread_t send_tid, recv_tid;

    int fd; // 全局文件描述符，供线程共享
    volatile int keep_running = 1; // 控制线程退出的变量
    // bool keep_running = true; // 控制线程退出的变量

    void autoSerial();

private:
    bool close0 = 0;     //为1时关闭

    void serialPreprocessor();      //预处理
    static int set_opt(int fd, int nSpeed, int nBits, char nEvent, int nStop);
    void* send_thread(void *arg);   //成员函数
    static void* start_send_thread(void* arg)   //静态适配器函数
    {
            auto* serial0 = static_cast<Serial*>(arg);
            return serial0->send_thread(arg);
    };
    void* receive_thread(void *arg) const;  //成员函数
    static void* start_receive_thread(void* arg)
    {
        auto* serial1 = static_cast<Serial*>(arg);
        return serial1->receive_thread(arg);
    };
    void * monitor_thread(void* arg);
    static void* start_monitor_thread(void* arg)
    {
        auto* serial = static_cast<Serial*>(arg);
        return serial->monitor_thread(arg);
    };
    void closeSerial();
};

